[GlobalSetup] publicvoidSetup() { // Setup configuration var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); _configuration = builder.Build(); _connectionString = _configuration.GetConnectionString("DefaultConnection");
// Setup DbContext var options = new DbContextOptionsBuilder<TestContext>() .UseSqlServer(_connectionString) .Options; _context = new TestContext(options);
// Ensure database exists and setup test data EnsureDatabaseExists(); }
// 添加測試資料 var random = new Random(42); // 使用固定的種子以確保測試資料一致性 var testData = Enumerable.Range(1, TestDataCount).Select(i => new TestEntity { Name = $"Test Entity {i}", CreateTime = DateTime.Today.AddDays(-random.Next(30)), Value = random.Next(1, 1000) }); _context.TestEntities.AddRange(testData); _context.SaveChanges(); }
[Benchmark(Baseline = true, Description = "使用 DI 注入的 DbContext")] publicasync Task<(int count, decimal average)> WithDI() { var result = await _context.TestEntities .Where(x => x.CreateTime >= DateTime.Today.AddDays(-7)) .ToListAsync();